package com.cili.learning.springbootwebsocket.websockethandler;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

/**
 * @author 码头薯条Pro
 * @date 2025/7/14 23:30
 * <p></p>
 * <p>
 * 视频讲解链接：
 * <p>
 * 题解链接：
 * <p>
 * 题目链接：
 */
@Slf4j
public class MyWebSocketHandler extends TextWebSocketHandler {
    // 用于保存所有连接的会话
    private static final Set<WebSocketSession> sessions = Collections.synchronizedSet(new HashSet<>());

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String query = Objects.requireNonNull(session.getUri()).getQuery();
        Map<String, String> paramMap = splitQuery(query);
        String bondTypeListStr = paramMap.get("bondTypeList");
        if (StringUtils.isNotBlank(bondTypeListStr)) {
            ArrayList<String> bondTypeList = new ArrayList<>(Arrays.asList(bondTypeListStr.split(",")));
            session.getAttributes().put("bondTypeList", bondTypeList);
        }
        sessions.add(session);
    }

    private Map<String, String> splitQuery(String query) throws UnsupportedEncodingException {
        Map<String, String> query_pairs = new LinkedHashMap<>();
        if (query == null) return query_pairs;
        String[] pairs = query.split("&");
        for (String pair : pairs) {
            int idx = pair.indexOf("=");
            query_pairs.put(
                    URLDecoder.decode(pair.substring(0, idx), "UTF-8"),
                    URLDecoder.decode(pair.substring(idx + 1), "UTF-8")
            );
        }
        return query_pairs;
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("WEBSOCKET连接关闭了！");
        sessions.remove(session);
    }

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        log.info("客户端发送的数据是：{}", payload);
        try {
            if (StringUtils.isNotBlank(payload)) {
                Map params = new ObjectMapper().readValue(payload, Map.class);
                if (null != params && null != params.get("bondTypeList")) {
                    session.getAttributes().put("bondTypeList", params.get("bondTypeList"));
//                session.sendMessage(new TextMessage("查询条件改为: " + params.get("bondTypeList")));
                }

                MyWebSocketHandler.sendMessageToAll("查询债券品种条件改为: " + params.get("bondTypeList"));
            }
        } catch (Exception e) {
            log.error("解析客户端的消息报错了！");
            e.printStackTrace();
        }

    }

    // 服务器主动推送方法
    public static void sendMessageToAll(String message) throws Exception {
        synchronized (sessions) {
            for (WebSocketSession session : sessions) {
                if (session.isOpen()) {
                    Object conditionObj = session.getAttributes().get("bondTypeList");
                    List<String> bondTypeList = new ArrayList<>();
                    if (conditionObj instanceof List) {
                        bondTypeList = (List<String>) conditionObj;
                        log.info("过滤条件是：{}", JSON.toJSONString(bondTypeList));
                    }
                    session.sendMessage(new TextMessage(message + JSON.toJSONString(bondTypeList)));
                }
            }
        }
    }
}
